<template>
<div class="UserControl">
    <!-- 主要内容（form表单） -->

    <el-row>
        <el-col :span="24">
            <el-card>
                <el-col :span="6" style="padding-bottom: 15px">
                    <el-card>
                        <div slot="header" class="card-header">
                            <span>组织机构</span>
                            <el-button type="primary" size="medium" icon="el-icon-plus" @click="adduser(0)">新建</el-button>
                        </div>

                        <el-input placeholder="输入关键字进行过滤" maxlength="20" show-word-limit v-model="filterText">
                        </el-input>

                        <el-tree @node-click="selectUsers" class="filter-tree" :data="OrganizationTree" :props="defaultProps" :default-expand-all="false" :default-expanded-keys="[1]" :filter-node-method="filterNode" ref="tree">
                        </el-tree>
                    </el-card>
                </el-col>

                <!-- 右边 点击 组织机构 显示 详情 ，并且能够修改 -->
                <el-col :span="18" style="padding-bottom: 30px">

                    <el-form ref="selectOrganizationForm" label-width="100px" :disabled="typeof selectOrganizationForm.id === 'number'?false:true" :model="selectOrganizationForm" :rules="rulesSelectOrganizationForm">
                        <el-form-item label="机构名称" prop="name">
                            <el-input v-model="selectOrganizationForm.name" maxlength="10" show-word-limit></el-input>
                        </el-form-item>
                        <el-form-item label="机构简称" prop="abbreviation">
                            <el-input v-model="selectOrganizationForm.abbreviation" maxlength="10" show-word-limit></el-input>
                        </el-form-item>

                        <el-form-item label="上级机构"  :prop="selectOrganizationForm.organParent==0?
                        '':superior">
                            <el-cascader :disabled="selectOrganizationForm.organParent==0" v-model="selectOrganizationForm.superior" :options="OrganizationTree" :props="optionProps" @change="handleChange"  ref="superior"></el-cascader>
                        </el-form-item>

                        <el-form-item label="机构编号" prop="number">
                            <el-input v-model="selectOrganizationForm.number" maxlength="64" show-word-limit placeholder="请输入机构编码" :disabled="(selectOrganizationForm.children!=null)?true:false" ></el-input>
                            <span>{{selectOrganizationForm.children!=null?'当前机构编号存在下级关联,不可修改':''}}</span>
                        </el-form-item>
                        <el-form-item label="联系人" prop="linkman">
                            <el-input v-model="selectOrganizationForm.linkman" maxlength="15" show-word-limit></el-input>
                        </el-form-item>
                        <el-form-item label="联系电话" prop="phone">
                            <el-input v-model="selectOrganizationForm.phone" maxlength="11" show-word-limit></el-input>
                        </el-form-item>
                        <el-form-item label="所在地点" prop="selectArea">
                            <el-cascader v-model="selectOrganizationForm.selectArea" :options="city" @change="handleChange"></el-cascader>
                        </el-form-item>
                        <el-form-item label="详细地址" prop="selectDetails">
                            <el-input v-model="selectOrganizationForm.selectDetails" placeholder="详细地址" style="width: 100%" maxlength="150" show-word-limit></el-input>
                        </el-form-item>
                        <el-form-item label="备注">
                            <el-input type="textarea" maxlength="255" show-word-limit v-model="selectOrganizationForm.remark"></el-input>
                        </el-form-item>
                    </el-form>
                    <el-row v-if="selectOrganizationForm.id">
                        <el-col>
                            <el-button type="primary" @click="onEdit('selectOrganizationForm')" style="margin-right: 30px">修改
                            </el-button>
                            <el-button type="danger" :disabled="selectOrganizationForm.superior[0]==null?true:false" @click="onDelete(selectOrganizationForm.id)" style="margin-right: 30px">删除
                            </el-button>
                        </el-col>
                    </el-row>

                </el-col>

                <!-- 新建组织机构弹窗 -->
                <el-dialog :title="isAddOrEdit ? '新建组织机构' : '修改组织机构'" :visible.sync="dialogFormVisible" width="40%" :destroy-on-close="true">
                    <el-form ref="AddOrganizationForm" label-width="120px" :model="addOrganizationForm" :rules="rulesAddOrganizationForm">
                        <el-form-item label="机构名称" prop="name">
                            <el-input v-model="addOrganizationForm.name" maxlength="10" show-word-limit></el-input>
                        </el-form-item>
                        <el-form-item label="机构简称" prop="abbreviation">
                            <el-input v-model="addOrganizationForm.abbreviation" maxlength="10" show-word-limit></el-input>
                        </el-form-item>

                        <el-form-item label="上级机构" prop="superior">
                            <el-cascader v-model="addOrganizationForm.superior" :options="OrganizationTree" :props="optionProps" @change="handleChange"></el-cascader>
                        </el-form-item>

                        <el-form-item label="机构编号" prop="number">
                            <el-input v-model="addOrganizationForm.number" maxlength="64" show-word-limit placeholder="请输入机构编码"></el-input>
                        </el-form-item>

                        <el-form-item label="联系人" prop="linkman">
                            <el-input maxlength="15" show-word-limit v-model="addOrganizationForm.linkman"></el-input>
                        </el-form-item>

                        <el-form-item label="联系电话" prop="phone">
                            <el-input v-model="addOrganizationForm.phone" maxlength="11" show-word-limit></el-input>
                        </el-form-item>

                        <el-form-item label="所在地点" class="morewidth" prop="addArea">
                            <el-cascader v-model="addOrganizationForm.addArea" :options="city" @change="handleChange"></el-cascader>
                        </el-form-item>
                        <el-form-item label="详细地址" prop="addDetails">
                            <el-input v-model="addOrganizationForm.addDetails" placeholder="详细地址" maxlength="150" show-word-limit></el-input>
                        </el-form-item>
                        <el-form-item label="备注">
                            <el-input type="textarea" maxlength="255" show-word-limit v-model="addOrganizationForm.remark"></el-input>
                        </el-form-item>
                    </el-form>

                    <el-row>
                        <el-col :span="24" class="text-center">
                            <el-button @click="dialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="onSubmit('AddOrganizationForm')">保存</el-button>
                        </el-col>
                    </el-row>
                </el-dialog>
            </el-card>
        </el-col>
    </el-row>
</div>
</template>

<script>
import {
    convertKey
} from "@/library";
import {
    mapGetters
} from "vuex";
import city from "./area.json";

export default {
    name: "UserControl",
    data() {
        return {
            addOrganizationForm: {
                name: "", //名称
                abbreviation: "", //简称
                superior: [
                ], //上级
                number: "", //编号
                linkman: "", //联系人
                phone: "", //电话
                remark: "", //备注
                addArea: [], // 省市区三级联动
                addDetails: '', // 详细地址
                detailedAddress: "", //详细地址汇总
            },

            selectOrganizationForm: {
                name: "", //名称
                abbreviation: "", //简称
                superior: [], //上级
                number: "", //编号
                linkman: "", //联系人
                phone: "", //电话
                remark: "", //备注
                selectArea: [], // 省市区三级联动
                selectDetails: '', // 详细地址
                detailedAddress: "", //详细地址汇总
            },
            tableData: [],
            // 总数据
            city: city,
            optionsLevel: [{
                value: 3,
                label: '区级管理员'
            }, {
                value: 4,
                label: '镇街管理员'
            }, {
                value: 5,
                label: '村居信息员'
            }],

            townIndex: 0,
            isAddOrigan: false,
            defaultProps: {
                children: "children",
                label: "label",
            },
            roleList: [],
            optionProps: {
                value: 'value',
                label: 'label',
                checkStrictly: true
            },
            filterText: "",
            dialogFormVisible: false,
            form: {
                account: "",
                userName: "",
                password: "",
                password2: "",
                organization: [],
                phone: "",
                userId: "",
                level: "",
                roleId: "",
                roleIds: [],
                idCard: "",
                subjectTownId: "", //所属镇 (区域编码) 必填
                subjectVillageId: "", //所属村 (区域编码)
                administrativeCode: "", //行政编码
            },
            search: "",
            checked: false,
            rulesSelectOrganizationForm: {
                name: [{
                    required: true,
                    message: "名称不能为空",
                    trigger: ["change", "blur"],
                }], //名称
                abbreviation: [{
                    required: true,
                    message: "简称不能为空",
                    trigger: ["change", "blur"],
                }], //简称
                superior: [{
                    required: true,
                    message: "上级不能为空",
                    trigger: ["change", "blur"],
                }], //上级
                number: [{
                    required: true,
                    message: "编号不能为空",
                    trigger: ["change", "blur"],
                }], //编号
                linkman: [{
                    required: true,
                    message: "联系人不能为空",
                    trigger: ["change", "blur"],
                }], //联系人
                phone: [{
                    required: true,
                    message: "联系电话不能为空",
                    trigger: ["change", "blur"],
                }], //电话
                remark: [{
                    required: true,
                    message: "备注不能为空",
                    trigger: ["change", "blur"],
                }], //备注
                selectArea: [{
                    required: true,
                    message: "所在省市区不能为空",
                    trigger: ["change", "blur"],
                }], // 省市区三级联动
                selectDetails: [{
                    required: true,
                    message: "详细地址不能为空",
                    trigger: ["change", "blur"],
                }], // 详细地址
                detailedAddress: [{
                    required: true,
                    message: "详细地址汇总不能为空",
                    trigger: ["change", "blur"],
                }], //详细地址汇总

            },
            rulesAddOrganizationForm: {
                name: [{
                    required: true,
                    message: "名称不能为空",
                    trigger: ["change", "blur"],
                }], //名称
                abbreviation: [{
                    required: true,
                    message: "简称不能为空",
                    trigger: ["change", "blur"],
                }], //简称
                superior: [{
                    required: true,
                    message: "上级不能为空",
                    trigger: ["change", "blur"],
                }], //上级
                number: [{
                    required: true,
                    message: "编号不能为空",
                    trigger: ["change", "blur"],
                }], //编号
                linkman: [{
                    required: true,
                    message: "联系人不能为空",
                    trigger: ["change", "blur"],
                }], //联系人
                phone: [{
                    required: true,
                    message: "联系电话不能为空",
                    trigger: ["change", "blur"],
                }], //电话
                remark: [{
                    required: true,
                    message: "备注不能为空",
                    trigger: ["change", "blur"],
                }], //备注
                addArea: [{
                    required: true,
                    message: "所在省市区不能为空",
                    trigger: ["change", "blur"],
                }], // 省市区三级联动
                addDetails: [{
                    required: true,
                    message: "详细地址不能为空",
                    trigger: ["change", "blur"],
                }], // 详细地址
                detailedAddress: [{
                    required: true,
                    message: "详细地址汇总不能为空",
                    trigger: ["change", "blur"],
                }], //详细地址汇总

            },

            subjectTownId: [{
                required: true,
                message: "请至少选择一项",
                trigger: "change",
            }, ],

            props: {
                children: "children",
                label: "label",
            },
            params: {
                pageNumber: 1,
                pageSize: 10,
            },
            OrganizationTree: [],
            paging: {},
            List: [],
            OrganizationList: [],
            row: {},
            disabled: false,
            lookdialogFormVisible: false,
            detail: {},
            documentClick: false,
            filterList: [],
            isAddOrEdit: true,
            //正则验证
            rules: {
                name: [{
                    required: true,
                    message: "请输入部门名称",
                    trigger: "blur",
                }, ],
                abbreviation: [{
                    required: true,
                    message: "请输入部门简称",
                    trigger: "blur",
                }, ],
                // superior: [{
                //     required: true,
                //     message: "请选择上级机构",
                //     trigger: "blur",
                // }],
                number: [{
                    required: true,
                    message: "请输入部门编号",
                    trigger: "blur",
                }],
                linkMan: [{
                    required: true,
                    message: "请输入联系人",
                    trigger: "blur",
                }],
                phone: [{
                    required: true,
                    message: "请输入联系电话",
                    trigger: "blur",
                }],
            },
        };
    },
    created() {
        this.Organization();
    },

    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        },
    },
    mounted() {
        // document.addEventListener('click', () => {
        //     if (this.documentClick) {
        //         this.UserControl()
        //         this.filterList = []
        //         this.documentClick = false
        //     }
        // })
    },
    computed: {
        ...mapGetters({
            options: "getTreeData/filtersVillage",
        }),
    },
    methods: {

        resetList() {
            this.filterList = []
        },

        changeOptions() {
            this.form.subjectVillageId = "";
        },
        getIndex(val) {
            this.townIndex = val;
        },
        selectUsers(data, e) {
            console.log(data.organParent)
            this.selectOrganizationForm.id = data.id
            this.selectOrganizationForm.name = data.label
            this.selectOrganizationForm.phone = data.linkPhone
            this.selectOrganizationForm.linkman = data.linkMan
            this.selectOrganizationForm.number = data.value
            this.selectOrganizationForm.abbreviation = data.organShortName
            this.selectOrganizationForm.organParent = data.organParent
            this.selectOrganizationForm.children = data.children
            let arr = []
            if (data.organParent == 0) {
                this.selectOrganizationForm.superior = 0
            } else {
                arr.push(e.parent.parent.data.value)
                arr.push(e.parent.data.value)
                if(arr[0] === undefined || arr[0] === null){
                    arr.shift()
                }
                this.selectOrganizationForm.superior = arr
            }
            this.selectOrganizationForm.selectArea = [data.provinceCode, data.cityCode, data.areaCode]
            this.selectOrganizationForm.selectDetails = data.detailAddress
        },

        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },

        // account: "",
        // userName: "",
        // password: "",
        // password2: "",
        // organization: [],
        // phone: "",
        // userId: "",
        // street: "",
        // level: "",
        // roleId: 3,

        adduser(id) {
            if (id > 0) {
                this.form.userId = id;
                this.isAddOrEdit = false;
            } else {
                this.form.userId = "";
                this.form.account = "";
                this.form.password = "";
                this.form.phone = "";
                this.isAddOrEdit = true;
            }
            this.$common.RolePermission(this.form).then((res) => {
                this.roleList = res.data.list;
                if (this.form.userId) {
                    this.$common.getUserDetailInfo(this.form).then((res) => {
                        console.log("userinfo", res)
                        this.form.account = res.data.list[0].username;
                        this.form.userName = res.data.list[0].realName;
                        this.form.phone = res.data.list[0].registerTele;
                        this.form.registerCard = res.data.list[0].idCard;
                        this.form.roleIds = res.data.list[0].roleIds;
                        this.form.level = res.data.list[0].userLevel;
                        if (res.data.list[0].userLevel == 4) {
                            this.form.subjectTownId = res.data.list[0].userAdministrativeCode;
                        }
                        if (res.page.list[0].userLevel == 5) {
                            this.form.subjectVillageId = res.data.list[0].userAdministrativeCode;
                        }
                        if (res.page.list[0].userLevel == 3) {
                            this.form.subjectTownId = "";
                            this.form.subjectVillageId = "";
                        }
                        this.disabled = false;
                        this.dialogFormVisible = true;
                    });
                } else {
                    this.disabled = false;
                    this.dialogFormVisible = true;
                }
            });
        },

        handleClick(row) {
            this.form = row;
            this.lookdialogFormVisible = true;
        },
        // 关闭弹框的事件
        closeDialog() {
            this.dialogFormVisible = false;
        },
        // 点击取消事件
        cancelFun() {
            this.dialogFormVisible = false;
        },

        //树形结构节点的点击事件
        handleNodeClick() {},
        statusChange(item) {
            console.log(item);
        },
        userStatusCn(index) {
            var Status = {
                0: "待审核",
                1: "审核通过",
                2: "审核不通过",
            };

            return Status[index];
        },

        handleSizeChange(pageSize) {
            this.params.pageSize = pageSize;
            this.UserControl(this.params.pageNumber, this.params.pageSize);
        },
        currentchange(pageNumber) {
            this.params.pageNumber = pageNumber;
            this.UserControl(this.params.pageNumber, this.params.pageSize);
        },

        Organization(pageNumber = 1, pageSize = 300) {
            this.$common.Organization(pageNumber, pageSize).then((res) => {
                console.log(res)
                this.OrganizationTree = res.data.list.reverse();

                // this.OrganizationTree.unshift({
                //     value: '0',
                //     label: '农业农村局',
                // })

                this.OrganizationTree = convertKey(this.OrganizationTree, {
                    organName: "label",
                    organCode: "value"
                });
            });
        },

        UserControl(pageNumber = 1, pageSize = 10) {
            this.$fishing.UserControl(pageNumber, pageSize).then((res) => {
                this.List = res.data.list;
                delete res.data.list;
                this.paging = res.data;
            });
        },
        handleChange(value) {
            console.log(value);
        },
        onDelete(id) {

            this.$confirm('此操作将永久删除此机构, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.post('rbac/sys/organ/delete', {
                    params: {
                        id
                    }
                }).then((res) => {
                	if (res.result === "success") {
						this.Organization()
						this.$message({
							type: 'success',
							message: '删除成功!'
						});

					} else if (res.result === "fail") {
						this.$message({
							type: 'error',
							message: res.errorMsg
						});
					}
                })


            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });

        },
        onEdit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.selectOrganizationForm.detailedAddress = this.selectOrganizationForm.selectArea[0] + "," + this.selectOrganizationForm.selectArea[1] + "," + this.selectOrganizationForm.selectArea[2] + "|" + this.selectOrganizationForm.selectDetails;
                    this.$fishing.createOriganOnSubmit(this.selectOrganizationForm).then((res) => {
                        if (res && res.errorCode == "00000") {
                            this.$message({
                                message: '编辑成功',
                                type: 'success',
                                duration: 1500,
                                onClose: () => {
                                    this.Organization()
                                }
                            })
                        } else {
                            this.$message.error(res.errorMsg)
                        }
                    })

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        onSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.addOrganizationForm.detailedAddress = this.addOrganizationForm.addArea[0] + "," + this.addOrganizationForm.addArea[1] + "," + this.addOrganizationForm.addArea[2] + "|" + this.addOrganizationForm.addDetails;

                    this.$fishing.createOriganOnSubmit(this.addOrganizationForm).then((res) => {
                        if (res && res.errorCode == "00000") {
                            this.$message({
                                message: '组织机构添加成功',
                                type: 'success',
                                duration: 1500,
                                onClose: () => {
                                    this.Organization()
                                    this.dialogFormVisible = false
                                }
                            })
                        } else {
                            this.$message.error(res.errorMsg)
                        }
                    })

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });

        },
        resetValues() {
            this.selectOrganizationForm = {}
        }
    },
};
</script>

<style lang="scss">
.UserControl {
    padding-bottom: 15px;

    .card-header {
        padding: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .form {
        padding: 15px 10px;
    }

    .el-card {
        width: 98%;
        margin: 15px auto 0;

        .bottom {
            display: flex;
            justify-content: flex-end;
            margin-top: 15px;
        }
    }
}
</style>
